package blogsys.demo.server.impl;

import blogsys.demo.bean.UserBlog;
import blogsys.demo.dao.UserBlogDao;
import blogsys.demo.server.UserBlogServer;
import blogsys.demo.utils.JsonResult;
import blogsys.demo.utils.JwtUtils;
import blogsys.demo.utils.ResultCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static blogsys.demo.utils.ResultCode.COMMON_FAIL;
import static blogsys.demo.utils.ResultCode.SUCCESS;

/**
 * 用户博客接口实现类
 */
@Service
public class UserBlogServerImpl implements UserBlogServer {
    private int pageSize = 10;

    @Autowired
    private UserBlogDao userBlogDao;
    /**
     * 查询所有的博客 一页十个
     * @param pageNum
     * @return
     */
    @Override
    public JsonResult getAllBolg(int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserBlog> userBlogs = userBlogDao.selectAllBlog();
        return new JsonResult(true, SUCCESS,new PageInfo(userBlogs));
    }

    /**
     * 对该用户添加一个博客
     *
     * 从token中获取
     * @param userBlog
     * @return
     */
    @Override
    public JsonResult addBlogById(HttpServletRequest request,UserBlog userBlog) {
        String id = JwtUtils.getIdByJwtToken(request);
        userBlog.setUserBlogUserId(id);
        userBlogDao.insertUserBlog(userBlog);
        return new JsonResult(true,ResultCode.SUCCESS_ADD);
    }

    /**
     * 从请求头中获取id的值
     * @param pageNum
     * @return
     */
    @Override
    public JsonResult getBlogById(HttpServletRequest request,int pageNum) {
        System.out.println(request);
        String id = JwtUtils.getIdByJwtToken(request);
        System.out.println(id+"==========================");
        PageHelper.startPage(pageNum, pageSize);
        System.out.println(id +" =============== ");
        List<UserBlog> userBlogs = userBlogDao.selectBlogByUserId(id);
        return new JsonResult(true,SUCCESS,new PageInfo<>(userBlogs));
    }


    /**
     * 删除一条博客
     * @param blogId
     * @return
     */
    @Override
    public JsonResult removeBlogById(String blogId) {
        int i = userBlogDao.deleteUserBlog(blogId);

        if(i == 1){
            return new JsonResult(true,SUCCESS);
        }else{
            return new JsonResult(false,COMMON_FAIL);
        }
    }

    /**
     * 修改博客内容
     * @param userBlog
     * @return
     */
    @Override
    public JsonResult updateBlog(UserBlog userBlog) {
        int i = userBlogDao.updateUserBlog(userBlog);

        if(i == 1){
            return new JsonResult(true,SUCCESS);
        }else{
            return new JsonResult(false,COMMON_FAIL);
        }
    }

}
